<script setup lang="ts">
defineOptions({
  name: "batchUploadMSDS"
});

import { ref, reactive } from "vue";
import type { FormInstance, FormRules } from "px-ui";
import { batchUpdateMSDSFiles } from "@/api/modules/operation";
import { useThrottleFn } from "@vueuse/core";
import { throttleDelay as delay } from "@/utils/constant";
import FileUpload from "@/components/Upload/FileUpload.vue";

interface Props {
  ids: Array<string>;
}

const props = withDefaults(defineProps<Props>(), {});

const dialogTableVisible = defineModel({ type: Boolean, default: false });

const loading = ref<boolean>(false);
const title = ref<string>("批量上传MSDS");
//  图片上传类型add：新增，edit：编辑，view：查看
const uploadType = ref<string>("add");
const fileList = ref<Array<any>>([]);

interface RuleForm {}
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({});

const rules = reactive<FormRules<RuleForm>>({});

const emits = defineEmits(["submit"]);

const cancelHandler = () => {
  dialogTableVisible.value = false;
};

const changeFileListHandler = (fl: Array<any>) => {
  fileList.value = [];
  if (!fl?.length) return;
  fileList.value = fl.map(item => item);
};

const submitHandler = useThrottleFn(async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true;
      const fileIds = fileList.value?.map(item => item.id);
      const fileNameList = fileList.value?.map(item => item.originalName);
      const { ids } = props;
      const params = { ids, fileIds, fileNameList };
      await batchUpdateMSDSFiles(params, () => {
        loading.value = false;
      });
      loading.value = false;
      emits("submit");
      dialogTableVisible.value = false;
    } else {
      console.error("error submit!", fields);
    }
  });
}, delay);
</script>

<template>
  <px-dialog v-model="dialogTableVisible" :title="title" :width="800">
    <px-form ref="ruleFormRef" v-loading="loading" :model="ruleForm" :rules="rules" inline label-width="100px" class="demo-ruleForm" status-icon>
      <px-row :gutter="32">
        <px-col :span="24">
          <px-form-item label="上传文档" prop="fileIdList" class="item-upload">
            <FileUpload :fileType="uploadType" :fileList="fileList" :countLimit="1" @changeFileList="changeFileListHandler" />
          </px-form-item>
        </px-col>
      </px-row>
    </px-form>
    <template #footer>
      <span class="dialog-footer">
        <px-button @click="cancelHandler">取消</px-button>
        <px-button type="primary" :loading="loading" @click="submitHandler"> 确认 </px-button>
      </span>
    </template>
  </px-dialog>
</template>

<style lang="scss" scoped>
:deep(.px-form-item) {
  width: 100%;

  .item-upload {
    .px-form-item__content {
      margin-left: 0 !important;
    }
  }

  .px-form-item__content {
    .px-input,
    .px-select,
    .px-date-picker,
    .px-time-picker,
    .px-tree-select {
      width: 100%;
    }
  }
}
</style>
